<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>碳排放计算器</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .history-item {
            cursor: pointer;
            margin-bottom: 5px;
        }
        .history-item:hover {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center">碳排放计算器</h1>
        <form id="carbonForm" class="mt-4">
            <div class="mb-3">
                <label for="processEmission" class="form-label">工艺排放 (吨):</label>
                <input type="number" class="form-control" id="processEmission" required>
            </div>
            <div class="mb-3">
                <label for="energyConsumption" class="form-label">能源消耗 (吨):</label>
                <input type="number" class="form-control" id="energyConsumption" required>
            </div>
            <div class="mb-3">
                <label for="resourceConsumption" class="form-label">资源消耗 (吨):</label>
                <input type="number" class="form-control" id="resourceConsumption" required>
            </div>
            <div class="mb-3">
                <label for="processFactor" class="form-label">工艺排放因子:</label>
                <input type="number" class="form-control" id="processFactor" value="0.22" required>
            </div>
            <div class="mb-3">
                <label for="energyFactor" class="form-label">能源消耗因子:</label>
                <input type="number" class="form-control" id="energyFactor" value="0.56" required>
            </div>
            <div class="mb-3">
                <label for="resourceFactor" class="form-label">资源消耗因子:</label>
                <input type="number" class="form-control" id="resourceFactor" value="0.33" required>
            </div>
            <button type="button" class="btn btn-primary w-100" id="calculateBtn">计算碳排放</button>
        </form>
        <div id="result" class="mt-4 text-center fs-5 fw-bold"></div>

        <h2 class="mt-5">历史记录</h2>
        <ul id="historyList" class="list-unstyled"></ul>

        <div class="d-flex gap-2 mt-4">
            <button class="btn btn-danger flex-grow-1" id="clearHistoryBtn">清除历史</button>
            <button class="btn btn-success flex-grow-1" id="saveHistoryBtn">保存历史</button>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
    <script>
    $(document).ready(function () {
        let db;

        // 初始化 SQL.js 数据库
        function initDatabase() {
            return new Promise((resolve, reject) => {
                const config = {
                    locateFile: (filename) => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${filename}`,
                };
                initSqlJs(config).then(SQL => {
                    db = new SQL.Database();
                    // 创建表
                    db.run(`
                        CREATE TABLE IF NOT EXISTS carbon_history (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            time TEXT NOT NULL,
                            process_emission REAL NOT NULL,
                            energy_consumption REAL NOT NULL,
                            resource_consumption REAL NOT NULL,
                            process_factor REAL NOT NULL,
                            energy_factor REAL NOT NULL,
                            resource_factor REAL NOT NULL,
                            total_carbon REAL NOT NULL
                        );
                    `);
                    resolve();
                }).catch(error => {
                    reject('无法初始化数据库');
                });
            });
        }

        // 添加历史记录
        function addHistoryRecord(record) {
            db.run(`
                INSERT INTO carbon_history (time, process_emission, energy_consumption, resource_consumption, process_factor, energy_factor, resource_factor, total_carbon)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?);
            `, [
                record.time,
                record.process_emission,
                record.energy_consumption,
                record.resource_consumption,
                record.process_factor,
                record.energy_factor,
                record.resource_factor,
                record.total_carbon
            ]);
        }

        // 获取所有历史记录
        function getAllHistoryRecords() {
            const result = db.exec(`
                SELECT * FROM carbon_history ORDER BY id DESC;
            `);
            if (result.length > 0) {
                return result[0].values.map(row => ({
                    id: row[0],
                    time: row[1],
                    process_emission: row[2],
                    energy_consumption: row[3],
                    resource_consumption: row[4],
                    process_factor: row[5],
                    energy_factor: row[6],
                    resource_factor: row[7],
                    total_carbon: row[8]
                }));
            }
            return [];
        }

        // 清除所有历史记录
        function clearHistoryRecords() {
            db.run(`
                DELETE FROM carbon_history;
            `);
        }

        // 初始化并加载历史记录
        initDatabase().then(() => {
            loadHistory();
        }).catch(error => {
            console.error(error);
        });

        // 加载历史记录
        function loadHistory() {
            const records = getAllHistoryRecords();
            $('#historyList').empty();
            records.forEach(record => {
                const li = $(`<li class="history-item" data-id="${record.id}">${record.time}</li>`);
                $('#historyList').append(li);
            });
        }

        // 计算碳排放
        $('#calculateBtn').click(function () {
            const processEmission = parseFloat($('#processEmission').val());
            const energyConsumption = parseFloat($('#energyConsumption').val());
            const resourceConsumption = parseFloat($('#resourceConsumption').val());
            const processFactor = parseFloat($('#processFactor').val());
            const energyFactor = parseFloat($('#energyFactor').val());
            const resourceFactor = parseFloat($('#resourceFactor').val());

            const totalCarbon = (processEmission * processFactor) +
                (energyConsumption * energyFactor) +
                (resourceConsumption * resourceFactor);

            $('#result').text(`总碳排放量: ${totalCarbon.toFixed(2)} 吨`);

            // 保存历史记录
            const timestamp = new Date().toLocaleString();
            const record = {
                time: timestamp,
                process_emission: processEmission,
                energy_consumption: energyConsumption,
                resource_consumption: resourceConsumption,
                process_factor: processFactor,
                energy_factor: energyFactor,
                resource_factor: resourceFactor,
                total_carbon: totalCarbon
            };

            addHistoryRecord(record);
            loadHistory();
        });

        // 点击历史记录显示详情
        $('#historyList').on('click', '.history-item', function () {
            const id = $(this).data('id');
            const records = getAllHistoryRecords();
            const record = records.find(r => r.id === id);
            if (record) {
                alert(`时间: ${record.time}\n输入: ${JSON.stringify({
                    process_emission: record.process_emission,
                    energy_consumption: record.energy_consumption,
                    resource_consumption: record.resource_consumption,
                    process_factor: record.process_factor,
                    energy_factor: record.energy_factor,
                    resource_factor: record.resource_factor
                })}\n结果: ${record.total_carbon.toFixed(2)} 吨`);
            }
        });

        // 清除历史记录
        $('#clearHistoryBtn').click(function () {
            clearHistoryRecords();
            loadHistory();
        });

        // 保存历史记录为 CSV 文件
        $('#saveHistoryBtn').click(function () {
            const records = getAllHistoryRecords();
            const headers = ["时间", "工艺排放 (吨)", "能源消耗 (吨)", "资源消耗 (吨)", "工艺排放因子", "能源消耗因子", "资源消耗因子", "总碳排放量 (吨)"];
            const rows = records.map(record => [
                record.time,
                record.process_emission,
                record.energy_consumption,
                record.resource_consumption,
                record.process_factor,
                record.energy_factor,
                record.resource_factor,
                record.total_carbon.toFixed(2)
            ]);

            const csvContent = "data:text/csv;charset=utf-8," +
                headers.join(",") + "\n" +
                rows.map(row => row.join(",")).join("\n");

            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "carbon_history.csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    });
    </script>
</body>
</html>